package com.lyx.list;

import java.io.Serializable;
import java.util.Arrays;

public class TestArrayList<E> extends TestAbstractList<E> implements TestList<E>, Serializable {

    private static final long serialVersionUID = 8683452581122892189L;
    //默认初始容量
    private static final int DEFAULT_CAPACITY = 10;

    //默认数组
    private static final Object[] EMPTY_ELEMENTDATA = {};

    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA ={};

    private int size;

    transient Object[] elementData;


    public TestArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;

    }

    @Override
    public boolean add(E e) {
        ensureCapacityInternal(size+1);
        elementData[size++] = e;
        return true;
    }

    @Override
    public E get(int index) {
        return null;
    }


    private void ensureCapacityInternal(int minCapacity){
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    /**
     * 判断是否是空数组
     * @param elementData
     * @param minCapacity
     * @return
     */
    private static int calculateCapacity(Object[] elementData,int minCapacity){
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA){
            return Math.max(DEFAULT_CAPACITY,minCapacity);
        }
        return minCapacity;
    }

    private void ensureExplicitCapacity(int minCapacity){
        modCount++;//为了线程安全
        //判断是否需要扩容
        if(minCapacity - elementData.length > 0){
            grow(minCapacity);
        }
    }
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    private void grow(int minCapacity){
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //如果新容量还比数组长度小，把最minCapacity给newCapacity
        if(newCapacity - minCapacity < 0){
            newCapacity = minCapacity;
        }
        //判断是否大于整数最大值-8
        if (newCapacity - MAX_ARRAY_SIZE > 0){
            newCapacity = hugeCapacity(minCapacity);
        }
        elementData = Arrays.copyOf(elementData,newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
    }


}
